package com.wstuo.itsm.updateRequest.service;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.itsm.updateRequest.dao.IUpdateRequestDAO;
import com.wstuo.itsm.updateRequest.dto.UpdateRequestDTO;
import com.wstuo.itsm.updateRequest.entity.UpdateRequest;
/**
 * 升级时间service class
 * @author Will
 *
 */
public class UpdateRequestService implements IUpdateRequestService{

	@Autowired
	private IUpdateRequestDAO updateRequestDAO;
	
	
	/**
	 * 保存升级时间
	 * @param dto
	 */
	@Transactional
	public void merge(UpdateRequestDTO dto){
		setTimeLong(dto);
		UpdateRequest entity=null;
		if(dto.getId()!=null){
			entity=updateRequestDAO.findById(dto.getId());
		}else{
			entity=new UpdateRequest();
		}
		UpdateRequestDTO.dto2entity(dto, entity);
		updateRequestDAO.merge(entity);
		
	}
	
	/**
	 * 设置时间长度
	 */
	public void setTimeLong(UpdateRequestDTO dto){
		Long timeLong=0L;
		if(dto.getDay()!=0){
			timeLong+=60*60*24*dto.getDay();
		}
		if(dto.getHour()!=0){
			timeLong+=60*60*dto.getHour();
		}
		if(dto.getMinute()!=0){
			timeLong+=60*dto.getMinute();
		}
		dto.setTimeLong(timeLong*1000);
	}
	/**
	 * 查询升级时间
	 * @return UpdateRequestDTO
	 */
	@Transactional
	public UpdateRequestDTO find(){
		List<UpdateRequest> entitys=updateRequestDAO.findAll();
		UpdateRequestDTO dto=new UpdateRequestDTO();
		if(entitys!=null && entitys.get(0)!=null){
			UpdateRequestDTO.entity2dto(entitys.get(0), dto);
			dto2entity(dto);
		}
		return dto;
		
	}
	/**
	 * dto to entity
	 * @param updateRequestDTO
	 * @param emtity
	 */
	private void dto2entity(UpdateRequestDTO updateRequestDTO){
		if(updateRequestDTO.getTimeLong()!=null){
			Long timeLong=updateRequestDTO.getTimeLong()/1000;
			int day=(int)(timeLong/(60*60*24));
			int hour=(int)(timeLong-(day*60*60*24))/(60*60);
			int minute=(int)(timeLong-day*60*60*24-60*60*hour)/60;
			updateRequestDTO.setDay(day);
			updateRequestDTO.setHour(hour);
			updateRequestDTO.setMinute(minute);
		}
	}
	/**
	 * 新增一条默认数据
	 */
	@Transactional
	public void saveUpdateRequest(){
		UpdateRequest entity=new UpdateRequest();
		entity.setCompanyNo(0L);
		entity.setCreateTime(new Date());
		entity.setEnable(true);
		entity.setTimeLong(60000L);
		updateRequestDAO.save(entity);
	}
}
